
import { Listbox, ListboxItem, ScrollShadow, Avatar, Button } from "@nextui-org/react";
import { PlusIcon } from "../..";
import { User } from "@/type/user";
import { useSelector } from "react-redux";
import { selectTeamDetail } from "@/lib/features/team/teamSlice";
import { invite } from "@/api/team/invite";
import { TeamUser } from "@/type/team";
import toast from "react-hot-toast";

export const ListboxWrapper = ({ children }: { children: React.ReactNode }) => (
    <div className="w-full px-1 py-2 rounded-small">
        <ScrollShadow className="max-h-[300px] ">
            {children}
        </ScrollShadow>

    </div>
);

export default function UserList({ users }: { users: User[] }) {

    const team = useSelector(selectTeamDetail)

    return (
        <ListboxWrapper>
            <Listbox
                items={users}
                emptyContent={
                    <>
                        <p className="text-center">无搜索目标</p>
                    </>
                }
                variant="flat"
            >

                {(item) => (
                    <ListboxItem key={item.user_id} textValue={item.username}>
                        <div className="flex gap-2 justify-between items-center">
                            <div className="flex gap-2 items-center">
                                <Avatar alt={item.username} className="flex-shrink-0" size="sm" />
                                <div className="flex flex-col">
                                    <span className="text-small">{item.username}</span>
                                    <span className="text-tiny text-default-400">{item.email}</span>
                                </div>
                            </div>
                            <Button key={item.user_id + "btn"} onPress={async () => {
                                const result = await invite({ t_id: team.team_id, u_id: item.user_id } as TeamUser)
                                if (result.code == 200) {
                                    toast.success(result.message)
                                } else {
                                    toast.error(result.message)
                                }
                            }} isIconOnly size="sm" color="primary">
                                <PlusIcon />
                            </Button>
                        </div>
                    </ListboxItem>
                )}

            </Listbox>
        </ListboxWrapper>
    );
}
